package com.sevenpay.wx.connection;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.sevenpay.wx.connection.bean.AccessTokenResponseBean;

/**
 * 获取accessToken工具类<br>
 * 需要设置httpClient，appId， appSecret属性后使用<br>
 * 
 * @author kunwang.li
 *
 */
public class AccessTokenUtil {
	
	private static Logger logger = LoggerFactory.getLogger(AccessTokenUtil.class);
	
	private String accessToken; // 获取到的凭证
	private String expiresIn; // 凭证有效时间，单位：秒
	private HttpClient httpClient;
	private String appId = null;
	private String appSecret = null;

	private static AccessTokenUtil accessTokenUtil;

	private AccessTokenUtil() {

	}

	public static AccessTokenUtil newInstance() {
		if (null == accessTokenUtil) {
			synchronized (AccessTokenUtil.class) {
				if (null == accessTokenUtil) {
					accessTokenUtil = new AccessTokenUtil();
				}
			}
		}
		return accessTokenUtil;
	}

	/**
	 * 获取当前的accessToken
	 * 
	 * @return
	 */
	public String getAccessToken() {
		if (null == accessToken) {
			refreshAccessToken(false);
		}
		return accessToken;
	}

	/**
	 * 刷新accessToken
	 * 
	 * @param force
	 *            false:当当前accessToken!=null时，不刷新 <br>
	 *            true: 强制刷新<br>
	 */
	public void refreshAccessToken(boolean force) {
		synchronized (accessTokenUtil) {
			if (force || null == accessToken) {
				String resMsg = null;
				try {
					resMsg = httpClient.send(WxUrlConstants.getUrl("accessToken", appId, appSecret), "",
							WxUrlConstants.charset);
				} catch (Exception e) {
					logger.error(e.getMessage(), e);
				}
				AccessTokenResponseBean atrb = JSONObject.parseObject(resMsg, AccessTokenResponseBean.class);
				this.accessToken = atrb.getAccessToken();
				this.expiresIn = atrb.getExpiresIn();
			}
		}
	}

	public HttpClient getHttpClient() {
		return httpClient;
	}

	public void setHttpClient(HttpClient httpClient) {
		this.httpClient = httpClient;
	}

	public String getExpiresIn() {
		return expiresIn;
	}

	public String getAppId() {
		return appId;
	}

	public void setAppId(String appId) {
		this.appId = appId;
	}

	public String getAppSecret() {
		return appSecret;
	}

	public void setAppSecret(String appSecret) {
		this.appSecret = appSecret;
	}

}
